package rd.hardcore.engine.datas 
{
	import com.carlcalderon.arthropod.Debug;
	import rd.hardcore.datas.Track;
	import rd.hardcore.params.GlobalParams;
	/**
	 * ...
	 * @author Fazermokeur
	 */
	public class GridDatasManager
	{
		private var _datas:XML;
		private var _vPads:Vector.<Track>;
		private var _uid:int;
		
		/*	Mappage clavier		*/
		private var azerty_keyCode:Array = [65, 90, 69, 82, 84, 89, 85, 73, 79, 80, 81, 83, 68, 70, 71, 72, 74, 75, 76, 77, 87, 88, 67, 86, 66, 78];
		private var qwerty_keyCode:Array = [81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76, 186, 90, 88, 67, 86, 66, 78];
		
		public function GridDatasManager(id:int) 
		{
			_vPads = new Vector.<Track>();
			_uid = id;
		}
		
		public function init(datas:XML, tracksXML:XML):void
		{
			_datas = datas;
			var tracksList:XML = tracksXML;
			var node:XML;
			var t:Track;
			for each (node in datas.pad) 
			{
				t = new Track();
				t.build(tracksList.track.(@keyId == node.@keyId)[0]);
				t.cpt = node.@hit;
				_vPads.push(t);
			}
			
		}
		
		public function getPadManagerNode():XML
		{
			var keyMapref:Array = (GlobalParams.AZERTY_MODE)?azerty_keyCode:qwerty_keyCode;
			
			var len:int = _vPads.length;
			var datas:String = "<padmanager id=\""+uid+"\">"+"\n";
			var t:Track;
			for (var i:int = 0; i < len; i++) 
			{
				t = _vPads[i];
				datas = datas + "<pad keyId=\""+t.keyId+"\" pos=\"11\" hit=\""+t.cpt+"\"><![CDATA["+keyMapref[i]+"]]></pad>"+"\n";
			}
			datas = datas + "</padmanager>";
			
			return new XML(datas);
		}
		
		public function getXMLTracksList():XMLList
		{
			var datas:XML= <abstractNode/>;
			var len:int = _vPads.length;
			var t:Track;
			for (var i:int = 0; i < len; i++) 
			{
				t = _vPads[i];
				datas.appendChild(t.genChild());
			}
			return datas.track;
		}
		
		public function getTrackById(keyId:int):Track
		{
			var len:int = _vPads.length;
			var t:Track;
			for (var i:int = 0; i < len; i++) 
			{
				if (_vPads[i].keyId == keyId)	return _vPads[i];
			}
			return null;
		}
		
		public function firstEmptyPads():Number
		{
			var len:int = _vPads.length;
			var t:int;
			for (var i:int = 0; i < len; i++) 
			{
				if (_vPads[i].thumb == "medias/thumbs/empty.jpg" && _vPads[i].file == "medias/songs/empty.mp3")
					return _vPads[i].keyId;
			}
			return NaN;
		}
		
		public function checkUniqueFile(file:String, thumb:String):Boolean
		{
			var len:int = _vPads.length;
			var t:int;
			for (var i:int = 0; i < len; i++) 
			{
				Debug.log(_vPads[i].file);
				Debug.log(file);
				if (_vPads[i].file == file && _vPads[i].thumb == thumb) {
					Debug.log("RETURN TRUE " + i);
					return true;
				}
			}
			
			return false;
		}
		
		public function get uid():int { return _uid; }
		
	}

}